const Router = require('koa-router')
const { Auth } = require('../../core/middleware/auth')
const router = new Router()
const { upLoad } = require('./xxxx')
const fs = require('fs')
router.post('/v1/upload/uploadfiles', upLoad.single('file'), (ctx) => {
    // 获取文件名称与文件所在路径
    let imgs = []
    let files
    if (Object.prototype.toString.call(ctx.request.files.file) == "[object Array]") {
        files = ctx.request.files.file
    } else {
        files = [ctx.request.files.file]
    }
    for (let index = 0; index < files.length; index++) {
        const file = files[index];
        const { name: filename, path } = file;
        // 创建文件输入流
        const fileReader = fs.createReadStream(path);
        // 文件将要的存放文件夹路径
        const fileDir = `public/uploads`;

        // 判断目录是否存在,目录不存在则创建
        if (!fs.existsSync(fileDir)) {
            try {
                fs.mkdirSync(fileDir);
            } catch (e) {
                console.error(e);
            }
        }

        // 保存文件的最终路径 (文件夹路径+文件名)
        const filepath = `${fileDir}/${filename}`;
        // 创建文件输出流
        const fileWriter = fs.createWriteStream(filepath);

        // 写入文件数据
        fileReader.pipe(fileWriter);

        // 至此文件已上传完成

        imgs.push(`https://www.ocean.black/uploads/${filename}`)
    }
    const imgStr = imgs.join(',')
    ctx.body = {
        // filename: ctx.request.files.file,
        url: imgStr,
        data: {
            url: imgStr,
            "alt": "", // 图片描述文字，非必须
            "href": "" // 图片的链接，非必须
        },
        errno: 0,
        code: 200
    }
})
module.exports = router

